package com.neteast.androidclient.contact.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONObject;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.adapter.GroupAdapter;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactData;
import com.neteast.androidclient.contact.util.FileUtil;
import com.neteast.androidclient.contact.util.ImageUtil;
import com.neteast.androidclient.contact.util.JsonUtil;
import com.neteast.androidclient.contact.util.LoginUtil;
import com.neteast.androidclient.contact.util.NetUtil;
import com.neteast.androidclient.contact.util.PinYinUtil;
import com.neteast.androidclient.contact.util.ValidateUtil;
import com.neteast.androidclient.contact.widget.ContactContainer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 联系人编辑页面
 * 
 * @author tiangh 2012-4-2 上午10:12:43
 */
public class ContactEditActivity extends Activity implements Runnable {
	/**相册图片*/
	private static final int GET_PHOTO_FROM_GALLERY = 0;
	/**拍照*/
	private static final int TAKING_PICTURE = 1;
	/**保存联系人成功*/
	private static final int SAVE_CONTACT_SUCCESS = 0;
	/**新增联系人失败*/
	private static final int ADD_CONTACT_ERROR = 1;
	/**修改联系人失败*/
	private static final int EDIT_CONTACT_ERROR = 2;
	/**打开新的照片编辑窗口*/
	private static final int OPEN_WIN_PHOTO = 3;
	/**头像上传成功 */
	protected static final int PHOTO_UPLOAD_FINISHED = 4;
	/**头像上传失败 */
	protected static final int PHOTO_UPLOAD_ERROR = 5;
	
	/**联系人*/
	private Contact contact;
	/**若是编辑联系人时，联系人的备份，用来确定联系人是否发生改动*/
	private Contact cloneContact;
	/**是否是新增联系人*/
	private boolean isNew;
	/**是否是云好友*/
	private boolean isCloud;
	
	/**存储地址信息的容器*/
	private ContactContainer locationContainer;
	/**存储im信息的容器*/
	private ContactContainer imContainer;
	/**存储email信息的容器*/
	private ContactContainer emailContainer;
	/**存储电话信息的容器*/
	private ContactContainer phoneContainer;
	/**联系人照片*/
	private Bitmap facePic;
	
	private Activity context;
	private LayoutInflater inflater;
	
	/**姓名*/
	private EditText etName;
	/**常用手机，若是云好友，则该手机是他的绑定手机*/
	private EditText etFphone;
	/**常用邮箱*/
	private EditText etFemail;
	/**公司*/
	private EditText etOrg;
	/**职位*/
	private EditText etJob;
	/**备注*/
	private EditText etRemark;
	/**分组信息*/
	private TextView tvGroup;
	/**照片*/
	private ImageView ivFacePic;
	
	/**没有头像时，选择头像窗口的列表项*/
	private String[] photoValue1=new String[]{"相册图片", "拍照"};
	/**有头像时，选择头像窗口的列表项*/
	private String[] photoValue2=new String[]{"删除头像", "更换头像"};
	/**头像窗口列表项的装载容器，适配器使用*/
	private ArrayList<String> photoValue=new ArrayList<String>();
	
	/**选择头像窗口的适配器*/
	private ArrayAdapter<String> photoAdapter;
	/**分组信息适配器*/
	private GroupAdapter groupAdapter;
	
	/**分组窗口*/
	private PopupWindow winGroup;
	/**增加信息项窗口*/
	private PopupWindow winAddItem;
	/**选择头像窗口*/
	private PopupWindow winSelectPhoto;
	/**退出确认窗口*/
	private PopupWindow winCancelConfirm;
	/**进度条对话框*/
	private ProgressDialog dialogSaveContact;
	/**进度条对话框，上传头像的对话框*/
	private ProgressDialog dialogUploadPhoto;
	/**联系人头像的本地缓存路径*/
	private String localPhoto;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_contact_edit);
		getWindow().setLayout(415, WindowManager.LayoutParams.MATCH_PARENT);
		context = ContactEditActivity.this;
		Bundle extras = getIntent().getExtras();
		isNew = extras.getBoolean("isNew");
		if (isNew) {
			contact = new Contact();
			contact.ownId=LoginUtil.getLastLoginUserId(this);
		} else {
			contact = (Contact) extras.getSerializable("contact");
			cloneContact = contact.clone();
		}
		init();
	}

	private void init() {
		isCloud = isCloud();
		inflater = LayoutInflater.from(context);
		initTitle();
		initName();
		initFphone();
		initFemail();
		initContainer();
		initPhoto();
		initGroup();
		initOrg();
		initRemark();
		createAddItemWindow();
		createCancelConfirmWindow();
		createSetGroupWindow();
		createSetPhotoWindow();
		createProgressDialog();
	}

	/**
	 * 创建进度条窗口
	 */
	private void createProgressDialog() {
		dialogSaveContact = new ProgressDialog(context);
		dialogSaveContact.setMessage("正在保存联系人...");
		dialogSaveContact.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
		dialogUploadPhoto = new ProgressDialog(context);
		dialogUploadPhoto.setMessage("正在保存头像...");
		dialogUploadPhoto.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	}
	/**
	 * 初始化常用手机，若是云好友，则不可以编辑
	 */
	private void initFphone() {
		View root = findViewById(R.id.contact_fphone);
		TextView tvLabel=(TextView) root.findViewById(R.id.item_label);
		tvLabel.setText("常用手机");
		tvLabel.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		etFphone = (EditText) root.findViewById(R.id.item_content);
		etFphone.setHint("请输入电话");
		etFphone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		root.findViewById(R.id.item_delitem).setVisibility(View.GONE);
		fillET(etFphone,contact.fphone);
		if (isCloud) {
			etFphone.setEnabled(false);
		}
	}
	/**
	 * 初始化常用邮箱，若是云好友，则不可以编辑
	 */
	private void initFemail() {
		View root = findViewById(R.id.contact_femail);
		TextView tvLabel=(TextView) root.findViewById(R.id.item_label);
		tvLabel.setText("常用邮箱");
		tvLabel.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		etFemail = (EditText) root.findViewById(R.id.item_content);
		etFemail.setHint("请输入邮箱");
		etFemail.setInputType(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		root.findViewById(R.id.item_delitem).setVisibility(View.GONE);
		fillET(etFemail,contact.femail);
		//是云好友，并且该项没有值，则隐藏
		if (isCloud) {
			etFemail.setEnabled(false);
			if (!isNotEmpty(contact.femail)) {
				root.setVisibility(View.GONE);
			}
		}
	}
	/**
	 * 初始化退出确认的窗口
	 */
	private void createCancelConfirmWindow() {
		View root = inflater.inflate(R.layout.dialog_list_view,null);
		root.findViewById(R.id.list).setVisibility(View.GONE);
		((TextView)root.findViewById(R.id.title)).setText("温馨提示");
		TextView tvMessage = (TextView) root.findViewById(R.id.message);
		tvMessage.setText("是否放弃当前编辑？");
		tvMessage.setVisibility(View.VISIBLE);
		root.findViewById(R.id.bottom).setVisibility(View.VISIBLE);
		root.findViewById(R.id.btn_OK).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				winCancelConfirm.dismiss();
				finishAndNoSave();
			}
		});
		root.findViewById(R.id.btn_Cancel).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				winCancelConfirm.dismiss();
			}
		});
		winCancelConfirm = new PopupWindow(root,300, 160);
		winCancelConfirm.setFocusable(true);
	}
	/**
	 * 初始化公司和职位信息，若是云好友，则不可以编辑
	 */
	private void initOrg() {
		View root = findViewById(R.id.contact_org);
		TextView tvLabel=(TextView) root.findViewById(R.id.item_label);
		tvLabel.setText("公司");
		tvLabel.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		etOrg=(EditText) root.findViewById(R.id.item_content);
		etJob=(EditText) root.findViewById(R.id.item_content2);
		etJob.setVisibility(View.VISIBLE);
		root.findViewById(R.id.item_delitem).setVisibility(View.GONE);
		fillET(etOrg,contact.organization);
		fillET(etJob,contact.job);
		//若是云好友，且公司和职位信息都没有填，那么隐藏该项
		if (isCloud) {
			etOrg.setEnabled(false);
			etJob.setEnabled(false);
			if (!isNotEmpty(contact.organization)) {
				etOrg.setVisibility(View.GONE);
				if (!isNotEmpty(contact.job)) {
					root.setVisibility(View.GONE);
				}
			}else if (!isNotEmpty(contact.job)) {
				etJob.setVisibility(View.GONE);
			}
		}
	}
	/**
	 * 初始化备注
	 */
	private void initRemark() {
		View root = findViewById(R.id.contact_remark);
		LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		root.setLayoutParams(params);
		TextView tvLabel=(TextView) root.findViewById(R.id.item_label);
		tvLabel.setText("备注");
		tvLabel.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		etRemark=(EditText) root.findViewById(R.id.item_content);
		etRemark.setHint("请输入备注");
		root.findViewById(R.id.item_delitem).setVisibility(View.GONE);
		fillET(etRemark,contact.remark);
	}
	/**
	 * 初始化用户的分组信息
	 */
	private void initGroup() {
		tvGroup = (TextView) findViewById(R.id.group_details);
		tvGroup.setText(contact.groups);
	}
	/**
	 * 创建设置分组的窗口
	 */
	private void createSetGroupWindow() {
		View root = inflater.inflate(R.layout.dialog_list_view, null);
		((TextView)root.findViewById(R.id.title)).setText("请选择分组");
		root.findViewById(R.id.bottom).setVisibility(View.VISIBLE);
		final ArrayList<String> data=isCloud?MainActivity.cloudGroups:MainActivity.contactGroups;
		groupAdapter = new GroupAdapter(context,data,contact.groups);
		final ListView list=(ListView) root.findViewById(R.id.list);
		list.setAdapter(groupAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				CheckBox box=(CheckBox) view.findViewById(R.id.group_hander);
				box.setChecked(!box.isChecked());
			}
		});
		root.findViewById(R.id.btn_OK).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				tvGroup.setText(groupAdapter.getCheckedValue());
				contact.groups=groupAdapter.getCheckedValue();
				winGroup.dismiss();
				Toast.makeText(context, "设置分组成功", 300).show();
			}
		});
		root.findViewById(R.id.btn_Cancel).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				winGroup.dismiss();
			}
		});
		winGroup = new PopupWindow(root, 300, ViewGroup.LayoutParams.WRAP_CONTENT);
		winGroup.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
		winGroup.setFocusable(true);
	}
	/**
	 * 初始化联系人姓名，如是云好友则不可编辑
	 */
	private void initName() {
		etName = (EditText) findViewById(R.id.contact_name);
		fillET(etName,contact.displayName);
		if (isCloud) {
			etName.setEnabled(false);
		}
	}
	/**
	 * 用数据填充EditText
	 * @param et
	 * @param text
	 */
	private void fillET(EditText et, String text) {
		if (isNotEmpty(text)) {
			et.setText(text);
		}
	}
	/**
	 * 判断String是否不为空，因为可能传递null，所以额外判断
	 * @param value
	 * @return
	 */
	private boolean isNotEmpty(String value) {
		return value!=null&&!"".equals(value.trim())&&!"null".equals(value.trim());
	}
	/**
	 * 判断是否是云好友
	 * @return
	 */
	private boolean isCloud() {
		if (contact.ownId==contact.contactId) {
			return false;
		}else {
			return contact.isReadOnly;
		}
	}
	/**
	 * 初始化新增条目窗口
	 */
	private void createAddItemWindow() {
    	LinearLayout root = (LinearLayout) inflater.inflate(R.layout.dialog_list_view, null);
    	((TextView)root.findViewById(R.id.title)).setText("请选择类型");
    	ListView selectList=(ListView) root.findViewById(R.id.list);
    	ArrayList<String> types=new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.types)));
    	selectList.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item_text, types));
    	winAddItem = new PopupWindow(root, 300, 300);
    	winAddItem.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
    	winAddItem.setFocusable(true);
    	selectList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				switch (position) {
				case 0:
					phoneContainer.addItem();
					break;
				case 1:
					emailContainer.addItem();
					break;
				case 2:
					imContainer.addItem();
					break;
				case 3:
					locationContainer.addItem();
					break;
				}
				winAddItem.dismiss();
			}
		});
	}
	/**
	 * 初始化顶部的标题栏
	 * 若是我的信息，显示在左边，若是新建联系人和编辑联系人，则显示在右边
	 */
	private void initTitle() {
		findViewById(R.id.rightView).setVisibility(View.INVISIBLE);
		View back = findViewById(R.id.btn_back);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				context.finish();
			}
		});
		TextView titleTV=(TextView) findViewById(R.id.tv_title);
		//我的信息编辑状态
		if (contact.ownId==contact.contactId) {
			getWindow().setGravity(Gravity.LEFT);
			titleTV.setText(R.string.label_me_edit_title);
		}
		//联系人信息编辑状态
		else{
			getWindow().setGravity(Gravity.RIGHT);
			back.setVisibility(View.VISIBLE);
			String value=isNew?"新建联系人":"编辑联系人信息";
			titleTV.setText(value);
		}
	}
	/**
	 * 初始化容器，若是新建联系人则各容器新增一个编辑条目
	 * 若是编辑联系人，则将联系人内容填充条目
	 */
	private void initContainer() {
		phoneContainer = (ContactContainer) findViewById(R.id.contact_phones);
		emailContainer = (ContactContainer) findViewById(R.id.contact_emails);
		imContainer = (ContactContainer) findViewById(R.id.contact_ims);
		locationContainer = (ContactContainer) findViewById(R.id.contact_locations);
		if (isNew) {
			phoneContainer.addItem();
			emailContainer.addItem();
			imContainer.addItem();
			locationContainer.addItem();
		}else {
			fillContainerWithContactData(phoneContainer,contact.phones);
			fillContainerWithContactData(emailContainer,contact.emails);
			fillContainerWithContactData(imContainer,contact.ims);
			fillContainerWithContactData(locationContainer,contact.locations);
		}
	}
	/**
	 * 
	 * @param container
	 * @param datas
	 */
	private void fillContainerWithContactData(ContactContainer container, ArrayList<ContactData> datas) {
		int size = datas.size();
		ContactData data=null;
		for(int i=0;i<size;i++){
			data = datas.get(i);
			container.addItem(data);
		}
		data=null;
	}
	/**
	 * 
	 */
	private void initPhoto() {
		findViewById(R.id.widget_call_layout).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (isCloud) {
					Toast.makeText(context, "不能编辑云好友的头像", 300).show();
				}else {
					photoValue.clear();
					photoValue.addAll(Arrays.asList(contact.hasPhoto?photoValue2:photoValue1));
					photoAdapter.notifyDataSetChanged();
					winSelectPhoto.showAtLocation(getWindow().getDecorView(), Gravity.TOP|Gravity.RIGHT,10, 20);
				}
			}
		});
		ivFacePic = (ImageView) findViewById(R.id.contact_facepic);
		ImageView ivEditFlag = (ImageView) findViewById(R.id.face_photo_edit);
		Drawable d=getResources().getDrawable(isCloud?R.drawable.edit_flag_cloud:R.drawable.edit_photo_icon);
		ivEditFlag.setImageDrawable(d);
		photoValue.clear();
		//没有头像时，设置默认头像
		if (!contact.hasPhoto) {
			facePic=BitmapFactory.decodeResource(getResources(), R.drawable.default_face_pic);
			photoValue.addAll(Arrays.asList(photoValue1));
		}else{
			facePic=BitmapFactory.decodeFile(ImageUtil.getPhoto(context, contact.contactId));
			photoValue.addAll(Arrays.asList(photoValue2));
		}
		ivFacePic.setImageBitmap(facePic);
	}
	/**
	 * 初始化选择照片的窗口
	 */
	private void createSetPhotoWindow() {
		View root = inflater.inflate(R.layout.dialog_list_view, null);
		((TextView) root.findViewById(R.id.title)).setText("添加图片");
		ListView list = (ListView) root.findViewById(R.id.list);
		photoAdapter = new ArrayAdapter<String>(context,R.layout.list_item_text, photoValue);
		list.setAdapter(photoAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				String value = photoAdapter.getItem(position);
				if (value.equals("相册图片")) {
					selectPhotoFromGallery();
				}else if (value.equals("拍照")) {
					takingPicture();
				}else if (value.equals("删除头像")) {
					deletePhoto();
				}else {//更换头像
					changePhoto();
				}
				winSelectPhoto.dismiss();
			}
		});
		winSelectPhoto = new PopupWindow(root,300,180);
		winSelectPhoto.setFocusable(true);
		winSelectPhoto.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
	}
	//从图库选择照片
	private void selectPhotoFromGallery() {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		intent.putExtra("crop", "circle");
		intent.putExtra("noFaceDetection",true); 
		intent.putExtra("return-data", true);
		intent.putExtra("outputX", 240); 
		intent.putExtra("outputY", 240); 
		intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"select image"),GET_PHOTO_FROM_GALLERY);
	}

	// 拍照
	private void takingPicture() {
		Intent intent = new Intent();
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, TAKING_PICTURE);
	}
	//更换头像
	private void changePhoto() {
		photoValue.clear();
		photoValue.addAll(Arrays.asList(photoValue1));
		photoAdapter.notifyDataSetChanged();
		handler.sendEmptyMessage(OPEN_WIN_PHOTO);
		return;
	}
	//删除头像
	private void deletePhoto() {
		contact.photo="";
		if (!isNew) {
			ImageUtil.setPhoto(context, contact.contactId,null);
			Log.i("test", "photo"+ImageUtil.getPhoto(context, contact.contactId));
		}
		if (facePic!=null) {
			facePic.recycle();
		}
		facePic=BitmapFactory.decodeResource(getResources(), R.drawable.default_face_pic);
		ivFacePic.setImageBitmap(facePic);
		contact.hasPhoto=false;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode==Activity.RESULT_OK) {
			switch (requestCode) {
			case GET_PHOTO_FROM_GALLERY:
			case TAKING_PICTURE:
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				if (bm!=null) {
					try {
						saveAndShowPhoto(bm);
					} catch (IOException e) {
						Log.e("test", e.getMessage(),e);
					}
				}
				break;
			}
		}
	}
	/**
	 * 保存图片，并显示
	 * @param bitmap
	 * @throws IOException
	 */
	private void saveAndShowPhoto(final Bitmap bitmap) throws IOException {
		dialogUploadPhoto.show();
		new Thread(new Runnable() {
			public void run() {
				try {
					File file = FileUtil.createPhotoFile(context);
					localPhoto=file.getAbsolutePath();
					FileOutputStream fos = new FileOutputStream(file);
					bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
					contact.photo=NetUtil.uploadPhoto(context,file);
					contact.hasPhoto=true;
					handler.sendMessage(handler.obtainMessage(PHOTO_UPLOAD_FINISHED, bitmap));
				} catch (Exception e) {
					contact.hasPhoto=false;
					contact.photo=null;
					handler.sendEmptyMessage(PHOTO_UPLOAD_ERROR);
					Log.e("test", e.getMessage(),e);
				}
			}
		}).start();
	}
	/**
	 * 点击添加更多按钮
	 * @param view
	 */
	public void addMore(View view) {
		winAddItem.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
	}
	/**
	 * 点击保存按钮
	 * @param view
	 */
	public void done(View view) {
		
		String name = etName.getText().toString().trim();
		if (name.equals("")) {
			Toast.makeText(context, "姓名不能为空", 300).show();
			return;
		}
		contact.displayName=name;
		contact.sortKey=PinYinUtil.getSortKey(name);
		String fPhone = etFphone.getText().toString().trim();
		if (fPhone.equals("")) {
			Toast.makeText(context, "常用手机不能为空", 300).show();
			return;
		}else if (!ValidateUtil.validatePhone("常用手机", fPhone)) {
			Toast.makeText(context, "手机格式错误", 300).show();
			etFphone.requestFocus();
			return;
		}
		contact.fphone=fPhone;
		
		String fEmail=etFemail.getText().toString().trim();
		if (!TextUtils.isEmpty(fEmail)&&!ValidateUtil.validateEmail(fEmail)) {
			Toast.makeText(context, "邮箱格式错误", 300).show();
			etFemail.requestFocus();
			return;
		}
		contact.femail=fEmail;
		
		contact.clear();
		if (!phoneContainer.onDone(contact.phones)) 
			return;
		if (!emailContainer.onDone(contact.emails)) 
			return;
		if (!imContainer.onDone(contact.ims)) 
			return;
		if (!locationContainer.onDone(contact.locations)) 
			return;
		contact.organization=etOrg.getText().toString().trim();
		contact.job=etJob.getText().toString().trim();
		contact.remark=etRemark.getText().toString().trim();
		contact.groups=tvGroup.getText().toString().trim();
		dialogSaveContact.show();
		new Thread(this).start();
	}
	/**
	 * 点击取消按钮
	 * @param view
	 */
	public void cancel(View view) {
		winCancelConfirm.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
	}
	/**
	 * 点击分组按钮
	 * @param view
	 */
	public void clickGroup(View view) {
		groupAdapter.notifyDataSetChanged();
		winGroup.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
	}
	/**
	 * 关闭当前页面，不进行保存操作
	 */
	private void finishAndNoSave() {
		setResult(Activity.RESULT_CANCELED);
		finish();
	}
	/**
	 * 关闭当前页面，并保存联系人
	 */
	private void finishAndSave(){
		Toast.makeText(context, "保存联系人成功", 300).show();
		dialogSaveContact.dismiss();
		Intent intent=new Intent();
		intent.putExtra("contact", contact);
		setResult(Activity.RESULT_OK, intent);
		finish();
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		winCancelConfirm.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
		return super.onTouchEvent(event);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			winCancelConfirm.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void run() {
		Looper.prepare();
		JSONObject json;
		if (isNew) {
			try {
				json= JsonUtil.translateContactToJson(contact);
				contact = NetUtil.addContact(context, json);
				if (contact.photo!=null) {
					ImageUtil.setPhoto(context, contact.contactId,localPhoto);
				}
			} catch (Exception e) {
				handler.sendEmptyMessage(ADD_CONTACT_ERROR);
				Log.i("test", e.getMessage(),e);
				return;
			}
		}else {
			try {
			contact.contactId=cloneContact.contactId;
			json = JsonUtil.isContactChanged(cloneContact, contact);
			if (json!=null) {
				Log.i("test", "json"+json.toString());
				contact=NetUtil.editContact(context, json);
				if (contact.photo!=null) {
					ImageUtil.setPhoto(context, contact.contactId,localPhoto);
				}
			}
			}catch (Exception e) {
				handler.sendEmptyMessage(EDIT_CONTACT_ERROR);
				Log.i("test", e.getMessage(),e);
				return;
			}
		}
		handler.sendEmptyMessage(SAVE_CONTACT_SUCCESS);
	}
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SAVE_CONTACT_SUCCESS:
				finishAndSave();
				break;
			case ADD_CONTACT_ERROR:
				Toast.makeText(context, "新增联系人失败", Toast.LENGTH_SHORT).show();
				dialogSaveContact.dismiss();
				break;
			case EDIT_CONTACT_ERROR:
				Toast.makeText(context, "编辑联系人失败", Toast.LENGTH_SHORT).show();
				dialogSaveContact.dismiss();
				break;
			case OPEN_WIN_PHOTO:
				winSelectPhoto.showAtLocation(getWindow().getDecorView(), Gravity.TOP|Gravity.RIGHT, 0, 0);
				break;
			case PHOTO_UPLOAD_FINISHED:
				Bitmap bitmap=(Bitmap) msg.obj;
				onPhotoUploadSuccess(bitmap);
				break;
			case PHOTO_UPLOAD_ERROR:
				onPhotoUploadError();
				break;
			}
		}
	};
	private void onPhotoUploadSuccess(Bitmap bitmap) {
		if (facePic!=null) {
			facePic.recycle();
		}
		facePic=bitmap;
		ivFacePic.setImageBitmap(facePic);
		dialogUploadPhoto.dismiss();
		Toast.makeText(context, "设置头像成功", Toast.LENGTH_SHORT).show();
	}
	
	private void onPhotoUploadError() {
		dialogUploadPhoto.dismiss();
		Toast.makeText(context, "设置头像错误", Toast.LENGTH_SHORT).show();
	}
}
